<template>
  <view class="history-panel">
    <scroll-view
      scroll-y
      class="history-scroll"
      @scrolltolower="loadMore"
    >
      <view v-if="historyTasks.length === 0 && !loading" class="empty">
        暂无生成记录
      </view>
      <view v-else class="history-grid">
        <view
          v-for="task in historyTasks"
          :key="task.taskId"
          class="history-item"
          @click="previewImage(task)"
        >
          <image
            v-if="task.status === 'COMPLETED' && task.imagePath"
            :src="baseurl + task.imagePath"
            class="history-image"
            mode="aspectFill"
          />
          <view v-else class="task-status">
            {{ getTaskStatusText(task.status) }}
          </view>
          <view class="history-info">
            <text class="history-date">{{ formatDateFromString(task.createdAt) }}</text>
            <text v-if="task.status === 'FAILED'" class="error-text">{{ task.errorMsg }}</text>
          </view>
        </view>
      </view>
      <view v-if="loading" class="loading-more">加载中...</view>
      <view v-if="noMoreData" class="no-more-data">没有更多记录了</view>
    </scroll-view>
    <!-- 预览大图 -->
    <view v-if="previewDialogVisible" class="preview-dialog" @click="previewDialogVisible = false">
      <image :src="selectedHistoryImage" class="preview-dialog-image" mode="aspectFit" />
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getUserTaskHistoryAPI } from '@/services/app'
import { baseurl } from '@/utils/http'

const historyTasks = ref([])
const currentPage = ref(0)
const pageSize = ref(10)
const loading = ref(false)
const noMoreData = ref(false)

const previewDialogVisible = ref(false)
const selectedHistoryImage = ref('')

const formatDate = (date) => {
  return new Intl.DateTimeFormat('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  }).format(date)
}
const formatDateFromString = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return formatDate(date)
}
const getTaskStatusText = (status) => {
  switch (status) {
    case 'QUEUED': return '等待中'
    case 'PROCESSING': return '生成中'
    case 'COMPLETED': return '已完成'
    case 'FAILED': return '失败'
    default: return status
  }
}
const loadHistoryTasks = async (page = 0) => {
  if (loading.value || (noMoreData.value && page > 0)) return
  loading.value = true
  console.log('~~~~~~~~~~~')
  try {
    const res = await getUserTaskHistoryAPI(page, pageSize.value)
    let tasks = []
    let last = false
    if (Array.isArray(res.result)) {
      tasks = res.result
      last = tasks.length < pageSize.value
    } else if (res.result && Array.isArray(res.result.content)) {
      tasks = res.result.content
      last = !!res.result.last
    }
    if (page === 0) {
      historyTasks.value = tasks
    } else {
      historyTasks.value = [...historyTasks.value, ...tasks]
    }
    noMoreData.value = last
    currentPage.value = page
  } catch (error) {
    uni.showToast({ title: '加载历史记录失败', icon: 'none' })
  } finally {
    loading.value = false
  }
}
const loadMore = () => {
  if (!loading.value && !noMoreData.value) {
    loadHistoryTasks(currentPage.value + 1)
  }
}
const previewImage = (task) => {
  if (task.status === 'COMPLETED' && task.imagePath) {
    selectedHistoryImage.value = baseurl + task.imagePath
    previewDialogVisible.value = true
  }
}
const refreshHistory = async () => {
  currentPage.value = 0
  noMoreData.value = false
  await loadHistoryTasks(0)
}
onMounted(() => {
  loadHistoryTasks(0)
})
defineExpose({ refreshHistory })
</script>

<style scoped>
.history-panel {
  height: 100%;
  background-color: #f5f7fa;
}
.history-scroll {
  height: 100vh;
}
.history-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 12rpx;
  padding: 12rpx;
}
.history-item {
  width: 48%;
  margin-bottom: 12rpx;
  background: #fff;
  border-radius: 8rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);
}
.history-image {
  width: 100%;
  height: 200rpx;
  object-fit: cover;
  border-radius: 8rpx 8rpx 0 0;
}
.task-status {
  height: 200rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #888;
  font-size: 28rpx;
  background: #f0f0f0;
}
.history-info {
  padding: 8rpx;
  font-size: 24rpx;
  color: #666;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.error-text {
  color: #f56c6c;
  margin-left: 8rpx;
}
.loading-more, .no-more-data {
  text-align: center;
  color: #888;
  font-size: 28rpx;
  padding: 20rpx 0;
}
.preview-dialog {
  position: fixed;
  left: 0; top: 0; right: 0; bottom: 0;
  background: rgba(0,0,0,0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
}
.preview-dialog-image {
  max-width: 90vw;
  max-height: 80vh;
  border-radius: 8rpx;
  background: #fff;
}
.empty {
  text-align: center;
  color: #888;
  font-size: 28rpx;
  padding: 40rpx 0;
}
</style> 